<template>
  <div class="app-container" style="padding:0">

    <div class="topLine">
      <!-- 搜索 -->
      <el-form ref="queryForm" :model="listQuery" :inline="true" label-width="68px">
        <el-form-item label="任务名称" prop="name">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入任务名称"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div>
        <!-- <el-button type="primary"  icon="el-icon-plus"  size="mini" >开始任务 </el-button> -->
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除 </el-button>
        <el-button type="primary" icon="el-icon-set-up" size="mini" :disabled="isTwoSelected" @click="startCompare">对比 </el-button>
      </div>

      <el-dialog title="数据对比" :visible.sync="showCompare" class="comparePop">
        <div class="compareTitle2">
          <span>课堂数据对比</span>
        </div>
        <div class="compareTitle">
          <span style="width:180px; flex: unset;">类目</span>
          <span style="width:240px; flex: unset;">类型</span>
          <span>课程1</span>
          <span>课程2</span>
        </div>

        <div class="compareBox">
          <div class="compareBox-label">行为统计</div>
          <div class="compareBox-right2">
            <div class="compareBox-right2-label">
              <span>老师</span>
              <span>学生</span>
            </div>
            <div class="compareBox-right">
              <div class="compareBox-right-line compareBox-right-line2"><span>教师讲授</span><span>{{ compareResults.id1.actions.s0 }}</span><span>{{ compareResults.id2.actions.s0 }}</span></div>
              <div class="compareBox-right-line compareBox-right-line2"><span>指导学生</span><span>{{ compareResults.id1.actions.s1 }}</span><span>{{ compareResults.id2.actions.s1 }}</span></div>
              <div class="compareBox-right-line compareBox-right-line2"><span>老师巡视</span><span>{{ compareResults.id1.actions.s2 }}</span><span>{{ compareResults.id2.actions.s2 }}</span></div>
              <div class="compareBox-right-line compareBox-right-line2"><span>学生汇报</span><span>{{ compareResults.id1.actions.t0 }}</span><span>{{ compareResults.id2.actions.t0 }}</span></div>
              <div class="compareBox-right-line compareBox-right-line2"><span>师生互动</span><span>{{ compareResults.id1.actions.t1 }}</span><span>{{ compareResults.id2.actions.t1 }}</span></div>
              <div class="compareBox-right-line compareBox-right-line2"><span>生生互动</span><span>{{ compareResults.id1.actions.t2 }}</span><span>{{ compareResults.id2.actions.t2 }}</span></div>
            </div>

          </div>
        </div>

        <div class="compareBox">
          <div class="compareBox-label">课堂时间分配</div>
          <div class="compareBox-right">
            <div class="compareBox-right-line"><span>学生活动时间</span><span>{{ compareResults.id1.dataST.s_time }}</span><span>{{ compareResults.id2.dataST.s_time }}</span></div>
            <div class="compareBox-right-line"><span>学生活动时间占比</span><span>{{ compareResults.id1.dataST.s_percent }}%</span><span>{{ compareResults.id2.dataST.s_percent }}%</span></div>
            <div class="compareBox-right-line"><span>教师授课时间</span><span>{{ compareResults.id1.dataST.t_time }}</span><span>{{ compareResults.id2.dataST.t_time }}</span></div>
            <div class="compareBox-right-line"><span>教师授课时间占比</span><span>{{ compareResults.id1.dataST.t_percent }}%</span><span>{{ compareResults.id2.dataST.t_percent }}%</span></div>
          </div>
        </div>

        <div class="compareBox">
          <div class="compareBox-label">RT-CH</div>
          <div class="compareBox-right">
            <div class="compareBox-right-line"><span>RT</span><span>{{ compareResults.id1.RtCh.Rt }}</span><span>{{ compareResults.id2.RtCh.Rt }}</span></div>
            <div class="compareBox-right-line"><span>CH</span><span>{{ compareResults.id1.RtCh.Ch }}</span><span>{{ compareResults.id1.RtCh.Ch }}</span></div>
            <div class="compareBox-right-line"><span>互动转换指数</span><span>{{ compareResults.id1.RtCh.reactRate }}%</span><span>{{ compareResults.id2.RtCh.reactRate }}%</span></div>
            <div class="compareBox-right-line"><span>互动类型</span><span>{{ compareResults.id1.RtCh.type }}</span><span>{{ compareResults.id1.RtCh.type }}</span></div>
          </div>
        </div>

        <div class="compareTitle2" style="margin-top: 30px;">
          <span>S-T教学行为分析对比</span>
        </div>

        <div class="ST-box">
          <div class="ST-box-item"><lineChart v-if="compareResults.id1.dataST.showST" :st-data="compareResults.id1.dataST.stData" :grid-set="compareResults.id1.dataST.gridSet" />课程1</div>
          <div class="ST-box-item"><lineChart v-if="compareResults.id2.dataST.showST" :st-data="compareResults.id2.dataST.stData" :grid-set="compareResults.id2.dataST.gridSet" />课程2</div>
        </div>

        <div class="compareTitle2" style="margin-top: 30px;">
          <span>数据结论</span>
        </div>
        <div>
          <p>通过对上述维度的数据进行分析，可以得出以下类型的结论：</p>

          <p> 1. ​​教学模式识别​​：课堂是“​​讲授主导型​​”（教师主导时间 > 70%）、“​​互动探究型​​”（师生互动+学生主动时间 > 50%）还是“​​练习巩固型​​”（练习巩固时间占比极高）？</p>
          <p> 2. ​​教学效率评估​​：​​无效/管理时间​​是否过长？课堂节奏是否紧凑？时间分配是否符合本节课（如复习课 vs 新授课）的目标？</p>
          <p> 3. ​学生主体性体现​​：学生在课堂中是被动的接收器还是主动的参与者？​​学生主动和互动时间​​的占比是衡量“以学生为中心”理念落实程度的关键指标。</p>
          <p>4. ​思维层次侧重​​：课堂时间是侧重于知识的灌输和记忆，还是侧重于​​高阶思维能力的培养​​？这直接关系到学生的核心素养发展。</p>
          <p> 5. ​​分配结构合理性​​：讲解、练习、评价反馈的时间分配是否合理？例如，是否存在“只讲不练”或“只练不评”的情况，导致教学效果打折扣。</p>
        </div>



      </el-dialog>

    </div>

    <el-table v-loading="loading" :data="list" empty-text="暂无数据" row-key="id" @select="handleSelect" @select-all="handleSelectAll">
      <el-table-column type="selection" width="55" align="center" reserve-selection />
      <el-table-column label="序号" type="index" align="center" width="50" />
      <el-table-column label="任务名称" align="center" prop="name" />
      <!-- <el-table-column label="任务描述" align="center" prop="description"  :show-overflow-tooltip="true" /> -->
      <!-- <el-table-column label="任务类型" align="center"  >
        <template slot-scope="scope">
          <div v-if="scope.row.type==1">ST教学分析</div>
          <div v-if="scope.row.type==2">会议督察</div>
        </template>
      </el-table-column> -->
      <el-table-column label="班级" align="center" prop="department.name" />
      <el-table-column label="采样时间" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.sampling_interval==5">5秒</div>
          <div v-if="scope.row.sampling_interval==15">15秒</div>
          <div v-if="scope.row.sampling_interval==30">30秒</div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="学生画面" align="center" prop="videoStream1" />
      <el-table-column label="老师画面" align="center" prop="videoStream2" /> -->
      <el-table-column label="开始时间" align="center" prop="start_time" width="160" />
      <el-table-column label="结束时间" align="center" prop="end_time" width="160" />
      <el-table-column label="任务状态" align="center" prop="status ">
        <template slot-scope="scope">
          <div v-if="scope.row.status==0">正在进行</div>
          <div v-if="scope.row.status==1">已结束</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="checkData(scope.row)"
          >查看数据
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getTaskList"
    />

  </div>
</template>

<script>

// 接口
import { getAllTask, getDataPfCh, getDataST, getDataRtCh, deleteHistory } from '@/api/main'
import { listDept } from '@/api/system/dept'
import lineChart from './charts/lineChart.vue'

import '@riophae/vue-treeselect/dist/vue-treeselect.css'
//import { number } from 'echarts'

export default {
  name: 'ClassList',
  components: { lineChart},
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      selectedRowKeys: [], // 存储选中行的唯一标识-----用于对比两组数据
      isTwoSelected: true, // 选中是否是两个数据---用于对比
      compareResults: {
        id1: {
          actions: {},
          dataST: {},
          RtCh: {}
        }, 
        id2: {
          actions: {},
          dataST: {},
          RtCh: {}
        }  
      },
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 字典表格数据
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      listQuery: {
        page: 1,
        limit: 10,
        name: undefined,
        type: 1
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        url: [
          { required: true, message: '地址不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '模板名称不能为空', trigger: 'blur' }
        ]
      },
      interval: null,
      // 组织树选项
      deptOptions: undefined,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      showCompare: false,
      reactType: '',
      showST: false,
      gridSet: {
        max: null,
        interval: null
      },
    }
  },
  watch: {
    // 根据名称筛选组织树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    // 获取历史任务
    this.getTaskList()
    // /////////
    this.getTreeselect()
  },
  methods: {

    /** 查询组织下拉树结构 */
    getTreeselect() {
      listDept().then(response => {
        this.deptOptions = response.data
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    // 获取历史任务
    getTaskList() {
      this.loading = true
      getAllTask(this.listQuery).then(response => {
        this.list = response.data.task_data

        this.list.forEach(item => {
          if (item.end_time) {
            item.end_time = item.end_time.replace('T', ' ')
          }
          if (item.start_time) {
            item.start_time = item.start_time.replace('T', ' ')
          }
        })
        this.total = response.data.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        code: undefined,
        description: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.listQuery.page = 1
      this.getTaskList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.listQuery = {
        page: 1,
        limit: 10,
        name: undefined,
        type: undefined
      }
      this.handleQuery()
    },


    // 处理选择
    handleSelect(selection, row) {
      // 更新选中的行ID数组
      if (selection.includes(row)) {
        // 如果包含当前行，则添加ID
        if (!this.selectedRowKeys.includes(row.id)) {
          this.selectedRowKeys.push(row.id)
        }
      } else {
        // 否则移除ID
        this.selectedRowKeys = this.selectedRowKeys.filter(id => id !== row.id)
      }
      // 判断selectedRowKeys是否是2个
      this.isTwoSelected = this.selectedRowKeys.length !== 2

      // 新增：同步更新ids、single、multiple状态
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 查看任务数据 */
    checkData(row) {
      const id = row.id
      this.$router.push({ path: '/classAnalysis', query: { id: id }})

     // getTaskDataById(id).then(response => {
        // this.interval = response.data.task_data.sampling_interval
        // 跳转
       
     // })
    },

    // 全选事件处理
    handleSelectAll(selection) {
      // 直接更新 selectedRowKeys 和 ids
      this.selectedRowKeys = selection.map(item => item.id)
      this.ids = [...this.selectedRowKeys] // 同步 ids
      
      // 更新按钮状态（根据你的业务需求调整）
      this.isTwoSelected = this.selectedRowKeys.length !== 2
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认此纪录?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return deleteHistory(ids)
      }).then(() => {
        this.getTaskList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },

    // 对比相关代码--------------------👇
    startCompare() {
      this.showCompare = true
      this.getDetail()
    },
    // 通过id获取数据
    async getDetail() {
        
      try {
        // 并行获取两个ID的所有数据
        const [id1Data, id2Data] = await Promise.all([
          this.getAllDataForId(this.selectedRowKeys[0]),
          this.getAllDataForId(this.selectedRowKeys[1])
        ])

        this.compareResults = {
          id1: id1Data,
          id2: id2Data
        };

      } catch (error) {
        console.error('获取详情数据失败:', error)
        this.$message.error('对比数据获取失败');
      }
    },
    // 并行获取该ID的所有数据
    async getAllDataForId(id) {
      const [actions, dataST, RtCh] = await Promise.all([
        this.getActions(id),
        this.getST(id),
        this.getRtCh(id)
      ])
      return{
        actions:{
          ...actions,
          s0: actions.s0,
          s1: actions.s1,
          s2: actions.s2,
          t0: actions.t0,
          t1: actions.t1,
          t2: actions.t2
        },
        dataST:{
          ...dataST,
          s_time: dataST.s_time,
          t_time: dataST.t_time,
          s_percent: dataST.s_percent,
          t_percent: dataST.t_percent,
          stData: dataST.stData,
          gridSet: dataST.gridSet,
          showST: dataST.showST
        },
        RtCh:{
          ...RtCh,          
          Rt: RtCh.Rt,
          Ch: RtCh.Ch,
          type: RtCh.type,
          reactRate: RtCh.reactRate
        }
      }
    },
    // 获取行为数据
    async getActions(id) {
      const res = await getDataPfCh(id)
      return{
        s0: res.data.s0_count,
        s1: res.data.s1_count,
        s2: res.data.s2_count,
        t0: res.data.t0_count,
        t1: res.data.t1_count,
        t2: res.data.t2_count
      }
    },
    // 获取st数据
    async getST(id) {
      const res = await getDataST(id)
      // st
      const stData = res.data.st_data    
      // 课堂百分比
      const s_percent = Number((res.data.s_percent * 100).toFixed(1))
      const t_percent = 100 - s_percent
      const sTime = Number((res.data.duration / 60 * s_percent / 100).toFixed(0))
      const tTime = Number((res.data.duration / 60 * t_percent / 100).toFixed(0))
      return{
        s_time: sTime,
        t_time: tTime,
        s_percent: s_percent,
        t_percent: t_percent,
        stData: stData,
        gridSet: this.setChartGrid(res.data.duration),
        showST: true
      }
    },
    // 获取Rt-Ch
    async getRtCh(id) {
      const res = await getDataRtCh(id)

      const x = res.data[0]
      const y = res.data[1]
      if (x > 0 && x <= 0.3 && y > 0 && y <= 0.6) {
        this.reactType = '练习型'
      } else if (x > 0.3 && x <= 0.7 && y > 0 && y <= 0.4) {
        this.reactType = '混合型'
      } else if (x > 0.7 && y <= 1 && y >= 0 && y <= 0.6) {
        this.reactType = '讲授型'
      } else {
        this.reactType = '对话型'
      }
      // 互动转换指数
      const reactRate = (y * 100).toFixed(2)
      return{
        Rt: res.data[0],
        Ch: res.data[1],
        type: this.reactType,
        reactRate: reactRate
      }
    },
    
    // ST图表样式间隔计算
    setChartGrid(length) {
      if (length <= 900) {
        this.gridSet.max = 900
        this.gridSet.interval = 60
      } else if (length > 900 && length <= 1800) {
        this.gridSet.max = 1800
        this.gridSet.interval = 120
      } else if (length > 1800 && length <= 2700) {
        this.gridSet.max = 2700
        this.gridSet.interval = 180
      } else if (length > 2700 && length <= 3600) {
        this.gridSet.max = 3600
        this.gridSet.interval = 300
      } else {
        const roundNum = Math.ceil(length / 50)
        this.gridSet.max = roundNum * 50
        this.gridSet.interval = (roundNum * 50) / 10
      }
      return this.gridSet

    },

























  }
}
</script>

<style>
.topLine{
  padding:20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
}
.el-table .el-table__header-wrapper th{
  background: #e1ecfa;
}
.topLine .el-form-item{
  margin-bottom: 0;
}

.comparePop{
}
.comparePop .el-dialog__body {
  max-height: 78vh; /* 限制最大高度（视窗高度的60%） */
  overflow-y: auto; /* 超出时显示滚动条 */
  padding: 10px 20px 50px; /* 可选，避免内容紧贴边缘 */
}
.compareTitle{
  height: 37px;
  background: #dce6f3;
  display: flex;
  align-items: center;
  color: #2d2d2d;
  font-size: 14px;
  border:1px solid #cfe0f4;
  border-bottom: none;
}
.compareTitle span{
  flex: 1;
  text-align: center;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right:1px solid #cfe0f4;
}
.compareTitle span:last-child{
  border-right:none;
}
.compareBox{
  background: #fbfbfb;
  border:1px solid #cfe0f4;
  min-height: 60px;
  display: flex;
}
.compareBox-label{
  width: 180px;
  flex-shrink: 0;
  border-right:1px solid #cfe0f4;
  display: flex;
  align-items: center;
  justify-content: center;
}
.compareBox-right{
  flex: 1;
  display: flex;
  display: flex;
  flex-direction: column;
}
.compareBox-right-line{
  height: 54px;
  display: flex;
  align-items: center;
  border-top:1px solid #cfe0f4;
}
.compareBox-right-line:first-child{
  border-top:none;
}
.compareBox-right-line:nth-child(2n){
  background: #f2f5fa;
}
.compareBox-right-line span{
  height: 100%;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right:1px solid #cfe0f4;  
  color: #dc8c00;
}
.compareBox-right-line span:first-child{
  width: 240px;
  flex: unset;
  color: #606266;
}
.compareBox-right-line span:last-child{
  border-right:none;  
}
.compareBox-right-line2{

}
.compareBox-right-line2 span:first-child{
  width:160px;
  flex: unset;
}



.compareBox-right2{
  display: flex;
  min-height: 40px;
  align-items: center;
  flex: 1;
}

.compareBox-right2-label{
  width: 80px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
  border-right:1px solid #cfe0f4;
}
.compareBox-right2-label span{
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}
.compareBox-right2-label span:first-child{  
  border-bottom:1px solid #cfe0f4;
}
.compareTitle2{
  height: 48px;
  background: #1264c1;
  background: linear-gradient(to right, rgba(0,88,189, 1), #fff);
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  color: #fff;
  font-size: 16px;
}
.compareTitle2 span{
  margin-left: 10px;
  border-left: 8px solid #fff;
  padding-left: 10px;
}
.ST-box{
  display: flex;
}
.ST-box-item{
  flex: 1;
  min-width: 200px;
  height: 300px;
  margin:0 20px 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
</style>
